// 全局变量
let downloadCount = 1234;
let appConfig = null; // 存储配置数据

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    loadConfig(function() {
        console.log('配置文件加载成功:', appConfig);
        applyConfigToPage();
        initializeApp();
    }, function(error) {
        console.error('配置文件加载失败，使用默认配置:', error);
        initializeApp();
    });
});

// 使用XMLHttpRequest加载配置文件
function loadConfig(onSuccess, onError) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', './config.json', true);
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    appConfig = JSON.parse(xhr.responseText);
                    if (onSuccess) onSuccess();
                } catch (e) {
                    console.error('配置文件JSON解析失败:', e);
                    if (onError) onError(e);
                }
            } else {
                console.error('配置文件加载失败，状态码:', xhr.status);
                if (onError) onError(new Error('HTTP ' + xhr.status));
            }
        }
    };
    
    xhr.onerror = function() {
        console.error('配置文件请求失败');
        if (onError) onError(new Error('Network Error'));
    };
    
    xhr.send();
}

// 应用配置到页面
function applyConfigToPage() {
    if (!appConfig) return;
    
    // 更新页面标题和meta信息
    updatePageMeta();
    
    // 更新页面内容
    updatePageContent();
    
    // 更新系统要求列表
    updateSystemRequirements();
    
    // 更新下载统计
    if (appConfig.stats) {
        downloadCount = appConfig.stats.downloads;
    }
}

// 更新页面meta信息
function updatePageMeta() {
    const title = document.querySelector('title[data-config]');
    if (title && appConfig.software) {
        title.textContent = appConfig.software.displayName;
    }
    
    const description = document.querySelector('meta[name="description"][data-config]');
    if (description && appConfig.software) {
        description.setAttribute('content', appConfig.software.description);
    }
    
    const keywords = document.querySelector('meta[name="keywords"][data-config]');
    if (keywords && appConfig.software) {
        keywords.setAttribute('content', appConfig.software.keywords);
    }
}

// 更新页面内容
function updatePageContent() {
    // 获取所有带有data-config属性的元素
    const configElements = document.querySelectorAll('[data-config]');
    
    configElements.forEach(element => {
        const configPath = element.getAttribute('data-config');
        const value = getConfigValue(configPath);
        
        if (value !== null) {
            // 处理版本号格式
            if (configPath === 'software.version' && !value.startsWith('v')) {
                element.textContent = 'v' + value;
            } else {
                element.textContent = value;
            }
        }
    });
}

// 更新系统要求列表
function updateSystemRequirements() {
    const requirementsList = document.querySelector('ul[data-config="system.requirements"]');
    if (requirementsList && appConfig.system && appConfig.system.requirements) {
        requirementsList.innerHTML = '';
        appConfig.system.requirements.forEach(requirement => {
            const li = document.createElement('li');
            li.textContent = requirement;
            requirementsList.appendChild(li);
        });
    }
}

// 根据路径获取配置值
function getConfigValue(path) {
    if (!appConfig) return null;
    
    const keys = path.split('.');
    let value = appConfig;
    
    for (const key of keys) {
        if (value && typeof value === 'object' && key in value) {
            value = value[key];
        } else {
            return null;
        }
    }
    
    return value;
}

// 初始化应用
function initializeApp() {
    setupNavigation();
    setupSmoothScrolling();
    setupDownloadButton();
    setupAnimations();
    updateDownloadStats();
    setupMobileMenu();
}

// 导航栏功能
function setupNavigation() {
    const navbar = document.querySelector('.navbar');
    
    // 滚动时改变导航栏样式
    window.addEventListener('scroll', function() {
        if (window.scrollY > 50) {
            navbar.style.background = 'rgba(10, 10, 10, 0.98)';
            navbar.style.boxShadow = '0 2px 20px rgba(0, 0, 0, 0.8)';
        } else {
            navbar.style.background = 'rgba(10, 10, 10, 0.95)';
            navbar.style.boxShadow = 'none';
        }
    });
}

// 平滑滚动
function setupSmoothScrolling() {
    const links = document.querySelectorAll('a[href^="#"]');
    
    links.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            const targetSection = document.querySelector(targetId);
            
            if (targetSection) {
                const offsetTop = targetSection.offsetTop - 70; // 考虑导航栏高度
                
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// 下载按钮功能
function setupDownloadButton() {
    const downloadBtn = document.getElementById('download-btn');
    const downloadZipBtn = document.getElementById('download-zip-btn');
    
    if (downloadBtn) {
        downloadBtn.addEventListener('click', function() {
            // 从配置文件或按钮属性获取下载信息
            const downloadUrl = getDownloadUrl(this, 'installer');
            const filename = getDownloadFilename(this, 'installer');
            const notificationMessage = getConfigValue('notifications.downloadInstaller') || '安装包下载已开始...';
            
            // 显示下载提示
            showDownloadNotification(notificationMessage);
            
            // 增加下载计数
            incrementDownloadCount();
            
            // 创建下载链接
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = filename;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 添加下载按钮动画
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
        });
    }
    
    if (downloadZipBtn) {
        downloadZipBtn.addEventListener('click', function() {
            // 从配置文件或按钮属性获取下载信息
            const downloadUrl = getDownloadUrl(this, 'portable');
            const filename = getDownloadFilename(this, 'portable');
            const notificationMessage = getConfigValue('notifications.downloadPortable') || '压缩包下载已开始...';
            
            // 显示下载提示
            showDownloadNotification(notificationMessage);
            
            // 增加下载计数
            incrementDownloadCount();
            
            // 创建下载链接
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = filename;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 添加下载按钮动画
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
        });
    }
}

// 获取下载URL
function getDownloadUrl(buttonElement, downloadType) {
    // 优先从按钮的data属性获取
    const urlFromAttr = buttonElement.getAttribute('data-config-url');
    if (urlFromAttr) {
        const configUrl = getConfigValue(urlFromAttr);
        if (configUrl) return configUrl;
    }
    
    // 从配置文件获取
    if (appConfig && appConfig.downloads) {
        if (downloadType === 'installer' && appConfig.downloads.installer) {
            return appConfig.downloads.installer.url;
        } else if (downloadType === 'portable' && appConfig.downloads.portable) {
            return appConfig.downloads.portable.url;
        }
    }
    
    // 默认值（向后兼容）
    return downloadType === 'installer' 
        ? 'http://10.169.128.20/files/automation-tools-platform/Automation%20Tools%20Platform%20Setup%200.1.1.exe'
        : 'http://10.169.128.20/files/automation-tools-platform/Automation%20Tools%20Platform%20Setup%200.1.1.zip';
}

// 获取下载文件名
function getDownloadFilename(buttonElement, downloadType) {
    // 优先从按钮的data属性获取
    const filenameFromAttr = buttonElement.getAttribute('data-config-filename');
    if (filenameFromAttr) {
        const configFilename = getConfigValue(filenameFromAttr);
        if (configFilename) return configFilename;
    }
    
    // 从配置文件获取
    if (appConfig && appConfig.downloads) {
        if (downloadType === 'installer' && appConfig.downloads.installer) {
            return appConfig.downloads.installer.filename;
        } else if (downloadType === 'portable' && appConfig.downloads.portable) {
            return appConfig.downloads.portable.filename;
        }
    }
    
    // 默认值（向后兼容）
    return downloadType === 'installer' 
        ? 'Automation Tools Platform Setup 0.1.1.exe'
        : 'Automation Tools Platform 0.1.1.zip';
}

// 显示下载通知
function showDownloadNotification(message = '下载已开始...') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = 'download-notification';
    notification.innerHTML = `
        <div class="notification-content">
            <i class="fas fa-download"></i>
            <span>${message}</span>
        </div>
    `;
    
    // 添加通知样式
    notification.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        background: var(--surface);
            color: var(--text-primary);
            border: 1px solid var(--border);
        padding: 15px 20px;
        border-radius: 12px;
        box-shadow: 0 8px 20px rgba(99, 102, 241, 0.3);
        z-index: 10000;
        transform: translateX(400px);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(400px)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 增加下载计数
function incrementDownloadCount() {
    downloadCount++;
    updateDownloadStats();
    
    // 保存到本地存储
    localStorage.setItem('downloadCount', downloadCount);
}

// 更新下载统计
function updateDownloadStats() {
    // 从本地存储获取下载计数
    const savedCount = localStorage.getItem('downloadCount');
    if (savedCount) {
        downloadCount = parseInt(savedCount);
    }
    
    // 更新页面上的下载计数
    const downloadCountElements = document.querySelectorAll('#download-count, #total-downloads');
    downloadCountElements.forEach(element => {
        if (element) {
            animateNumber(element, downloadCount);
        }
    });
}

// 数字动画
function animateNumber(element, targetNumber) {
    const startNumber = parseInt(element.textContent.replace(/,/g, '')) || 0;
    const duration = 1000;
    const startTime = Date.now();
    
    function updateNumber() {
        const elapsed = Date.now() - startTime;
        const progress = Math.min(elapsed / duration, 1);
        
        // 使用缓动函数
        const easeOutQuart = 1 - Math.pow(1 - progress, 4);
        const currentNumber = Math.floor(startNumber + (targetNumber - startNumber) * easeOutQuart);
        
        element.textContent = currentNumber.toLocaleString();
        
        if (progress < 1) {
            requestAnimationFrame(updateNumber);
        }
    }
    
    updateNumber();
}

// 设置动画
function setupAnimations() {
    // 滚动动画观察器
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-in');
            }
        });
    }, observerOptions);
    
    // 观察需要动画的元素
    const animateElements = document.querySelectorAll('.hero-content, .download-info, .about-text');
    animateElements.forEach(element => {
        observer.observe(element);
    });
    
    // 添加CSS动画类
    const style = document.createElement('style');
    style.textContent = `
        .hero-content,
        .download-info,
        .about-text {
            opacity: 0;
            transform: translateY(30px);
            transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .animate-in {
            opacity: 1 !important;
            transform: translateY(0) !important;
        }
        
        .hero-content {
            transition-delay: 0.2s;
        }
    `;
    document.head.appendChild(style);
}

// 移动端菜单
function setupMobileMenu() {
    const navToggle = document.querySelector('.nav-toggle');
    const navMenu = document.querySelector('.nav-menu');
    
    if (navToggle && navMenu) {
        navToggle.addEventListener('click', function() {
            navMenu.classList.toggle('active');
            navToggle.classList.toggle('active');
        });
        
        // 点击菜单项时关闭菜单
        const navLinks = document.querySelectorAll('.nav-menu a');
        navLinks.forEach(link => {
            link.addEventListener('click', function() {
                navMenu.classList.remove('active');
                navToggle.classList.remove('active');
            });
        });
    }
    
    // 添加移动端菜单样式
    const mobileStyle = document.createElement('style');
    mobileStyle.textContent = `
        @media (max-width: 768px) {
            .nav-menu {
                position: fixed;
                top: 70px;
                left: 0;
                width: 100%;
                height: calc(100vh - 70px);
                background: var(--surface);
                backdrop-filter: blur(10px);
                flex-direction: column;
                justify-content: flex-start;
                align-items: center;
                padding-top: 2rem;
                transform: translateX(-100%);
                transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
            
            .nav-menu.active {
                display: flex;
                transform: translateX(0);
            }
            
            .nav-menu li {
                margin: 1rem 0;
            }
            
            .nav-menu a {
                font-size: 1.2rem;
                padding: 1rem;
            }
            
            .nav-toggle.active span:nth-child(1) {
                transform: rotate(45deg) translate(5px, 5px);
            }
            
            .nav-toggle.active span:nth-child(2) {
                opacity: 0;
            }
            
            .nav-toggle.active span:nth-child(3) {
                transform: rotate(-45deg) translate(7px, -6px);
            }
        }
    `;
    document.head.appendChild(mobileStyle);
}

// 页面性能优化
function optimizePerformance() {
    // 图片懒加载
    const images = document.querySelectorAll('img[data-src]');
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
}

// 错误处理
window.addEventListener('error', function(e) {
    console.error('页面错误:', e.error);
    
    // 可以在这里添加错误报告逻辑
    // 例如发送错误信息到服务器
});

// 页面卸载时的清理
window.addEventListener('beforeunload', function() {
    // 保存用户数据或执行清理操作
    localStorage.setItem('lastVisit', Date.now());
});

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + D 快速下载
    if ((e.ctrlKey || e.metaKey) && e.key === 'd') {
        e.preventDefault();
        const downloadBtn = document.getElementById('download-btn');
        if (downloadBtn) {
            downloadBtn.click();
        }
    }
    
    // ESC 关闭移动端菜单
    if (e.key === 'Escape') {
        const navMenu = document.querySelector('.nav-menu');
        const navToggle = document.querySelector('.nav-toggle');
        if (navMenu && navMenu.classList.contains('active')) {
            navMenu.classList.remove('active');
            navToggle.classList.remove('active');
        }
    }
});

// 初始化性能优化
document.addEventListener('DOMContentLoaded', optimizePerformance);

// 页面可见性API - 当页面重新可见时更新数据
document.addEventListener('visibilitychange', function() {
    if (!document.hidden) {
        updateDownloadStats();
    }
});

// 添加一些实用工具函数
const utils = {
    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    // 节流函数
    throttle: function(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },
    
    // 格式化文件大小
    formatFileSize: function(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
};

// 导出工具函数供全局使用
window.utils = utils;